from sklearn.preprocessing import PolynomialFeatures 
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd#调用pandas库并命名为pd
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline


new_pumpkins =pd.read_csv("new_pumpkins.csv")#利用pandas库打开csv数据
print(new_pumpkins.head())#查看数据的前5行
new_pumpkins.info() #查看数据组织结构

# day_of_year = pd.to_datetime(new_pumpkins['Date']).apply(lambda dt: (dt-datetime(dt.year,1,1)).days)
plt.scatter('DayOfYear','Price',data=new_pumpkins) #DayOfYear为销售日期，绘制销售日期与价格的散点图

X = pd.get_dummies(new_pumpkins['Variety']) #以南瓜的类别作为特征变量，并转化数据类型
Y = new_pumpkins['Price'] #以价格为预测标签
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)#以8：2的比例划分数据集与训练集

pipeline = make_pipeline(PolynomialFeatures(2), LinearRegression())#构建自动化流程
pipeline.fit(X_train,Y_train)#训练模型
pred = pipeline.predict(X_test)#在测试集上预测结果并保存在pred变量中
rmse = np.sqrt(mean_squared_error(Y_test,pred))#计算RMSE
print(f'RMSE指标: {rmse:3.3} ({rmse/np.mean(pred)*100:3.3}%)')
score = pipeline.score(X_train,Y_train)#计算相关系数
print('相关系数: ', score)
plt.scatter(X_test,Y_test)#绘制散点图
plt.plot(X_test,pred)#绘制回归线，若多条回归线是因为X_test是随机未排序的，排序后可尝试解决
plt.show()